package com.cxlin.cwanandroid.ui.login.viewmodel

import androidx.lifecycle.viewModelScope
import com.cxlin.base.BaseViewModel
import com.cxlin.base.mvi.UiEvent
import com.cxlin.base.mvi.UiIntent
import com.cxlin.base.mvi.UiState
import com.cxlin.cwanandroid.model.repository.LoginRepository
import kotlinx.coroutines.launch
import com.cxlin.base.model.api.Result
import com.cxlin.cwanandroid.App
import com.cxlin.cwanandroid.model.bean.User
import com.cxlin.cwanandroid.store.MMKVManager
import kotlinx.coroutines.flow.update
import org.greenrobot.eventbus.EventBus

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/29 14:01
 */
class LoginViewModel(private val loginRepository: LoginRepository) : BaseViewModel() {

    // 状态
    sealed class LoginUiState : UiState {
        object Idel : LoginUiState()
        data class IsLoading(val result: Boolean) : LoginUiState()
        data class IsSuccess(val result: Boolean) : LoginUiState()
        data class EnableLoginBtn(val result: Boolean) : LoginUiState()
    }

    // 事假
    sealed class LoginEvent : UiEvent {
        class ToastEvent(val message: String, val short: Boolean = false) : LoginEvent()
    }

    // 意图
    sealed class LoginUiIntent : UiIntent {
        data class Login(val userName: String, val passWord: String) : LoginUiIntent()
        data class Register(val userName: String, val passWord: String) : LoginUiIntent()
        data class CheckEnableLoginBtn(val userName: String, val passWord: String) : LoginUiIntent()
    }


    override fun handleIntent(intent: UiIntent) {
        when (intent) {
            is LoginUiIntent.Login -> {
                viewModelScope.launch {
                    kotlin.runCatching {
                        mUiStateFlow.update { LoginUiState.IsLoading(true) }
                        val result = loginRepository.login(intent.userName, intent.passWord)
                        handleLoginResponse(result)
                    }
                }
            }

            is LoginUiIntent.Register -> {
                viewModelScope.launch {
                    kotlin.runCatching {
                        mUiStateFlow.update { LoginUiState.IsLoading(true) }
                        val result = loginRepository.register(intent.userName, intent.passWord)
                        handleLoginResponse(result)
                    }
                }
            }

            is LoginUiIntent.CheckEnableLoginBtn -> {
                if (intent.userName.isNotBlank() && intent.passWord.isNotBlank()) {
                    mUiStateFlow.update { LoginUiState.EnableLoginBtn(true) }
                } else {
                    mUiStateFlow.update { LoginUiState.EnableLoginBtn(false) }
                }
            }
        }

    }

    override fun createInitState(): UiState {
        return LoginUiState.Idel
    }

    private suspend fun handleLoginResponse(result: Result<User>) {
        if (result is Result.Success) {
            saveUser(result.data)
            mUiStateFlow.update { LoginUiState.IsSuccess(true) }
            mUiStateFlow.update { LoginUiState.IsLoading(false) }
            EventBus.getDefault().postSticky(com.cxlin.cwanandroid.event.LoginEvent())

        } else if (result is Result.Error) {
            mUiStateFlow.update { LoginUiState.IsLoading(false) }
            mEffectFlow.emit(LoginEvent.ToastEvent(result.exception.message ?: "网络异常", true))
        }
    }

    private fun saveUser(user: User?) {
        // 存储在内存中
        App.CURRENT_USER = user
        // 持久化存储
        MMKVManager.user = user
    }

}